import { computed, reactive } from 'vue'

export const getCartList = () => {
  let content = localStorage.getItem('cartList')
  if (!content) {
    content = '{}'
  }
  return reactive(JSON.parse(content))
}

function setCartList (cartList) {
  const value = JSON.stringify(cartList)
  localStorage.setItem('cartList', value)
}

export const useCartList = (shopId, cartList) => {
  const changeCount = (shopId, productId, product, number) => {
    let shop = cartList[shopId]
    if (!shop) {
      shop = { products: {} }
      cartList[shopId] = shop
    }
    if (!shop?.products?.[productId]) {
      shop.products[productId] = {
        count: 0,
        checked: true
      }
      shop.products[productId].info = product
    }
    if (number) {
      shop.products[productId].count += number
      shop.products[productId].checked = true
    }
    if (shop.products[productId].count < 0) {
      shop.products[productId].count = 0
    }
    setCartList(cartList)
  }
  const totalCount = computed(() => {
    const products = cartList[shopId]?.products || []
    let count = 0
    for (const key in products) {
      if (products[key].checked) {
        count += products[key].count
      }
    }
    return count
  })
  const allChecked = computed(() => {
    const products = cartList[shopId]?.products || []
    for (const key in products) {
      if (!products[key].checked) {
        return false
      }
    }
    return true
  })

  const totalAmount = computed(() => {
    const products = cartList[shopId]?.products || []
    let amount = 0
    for (const key in products) {
      if (products[key].checked) {
        amount += products[key].info.sellingPrice * products[key].count
      }
    }
    return amount.toFixed(2)
  })
  const clearCart = (shopId) => {
    cartList[shopId].products = {}
    setCartList(cartList)
  }
  const changeSelectedState = (shopId, productId) => {
    const checked = cartList[shopId].products[productId].checked
    cartList[shopId].products[productId].checked = !checked
    setCartList(cartList)
  }

  const changeAllProductState = (shopId) => {
    const products = cartList[shopId]?.products || []
    for (const key in products) {
      products[key].checked = true
    }
    setCartList(cartList)
  }

  return {
    cartList,
    totalCount,
    totalAmount,
    allChecked,
    changeCount,
    clearCart,
    changeSelectedState,
    changeAllProductState
  }
}
